package cn.ztydata.teachingsystem.heaven.dao;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.entity.Daily;
import cn.ztydata.teachingsystem.heaven.entity.DailyComment;
import cn.ztydata.teachingsystem.heaven.web.dto.SpecialtyGroup.DailyCommentDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 教学日志评论
 *
 * @author lyj
 * @since 2015/5/7
 */
@Repository
public class DailyCommentDao extends BaseDao{
    @Autowired
    private WebContext webContext;

    //<editor-fold desc="新增">
    /**
     * 新增教学日志评论
     *
     * @param dailyComment
     * @return void
     * @author lyj
     * @since 2015-5-7
     */
    public int addDailyComment(final DailyComment dailyComment) {
        StringBuilder sql = new StringBuilder("INSERT INTO t_daily_comment VALUES (NULL,:content,:dailyId,:commentId,:commentor,:creatorId,NOW())");

        MapSqlParameterSource param = new MapSqlParameterSource()
                .addValue("content", dailyComment.getContent())
                .addValue("dailyId", dailyComment.getDailyId())
                .addValue("commentId", dailyComment.getCommentId())
                .addValue("commentor", dailyComment.getCommentor())
                .addValue("creatorId", webContext.getUserId());

        log.debug("新增教学日志评论");
        return namedParameterJdbcTemplate.update(sql.toString(), param);
    }
    //</editor-fold>


    //<editor-fold desc="删除">
    /**
     * 根据ID删除评论（回复）
     *
     * @param id 回复ID
     * @return int
     * @author lyj
     * @since 2015-5-6
     */
    public int deleteById(final long id) {
        StringBuilder sql = new StringBuilder("DELETE FROM t_daily_comment WHERE id = :id ");

        log.debug("删除评论（回复）");
        return namedParameterJdbcTemplate.update(sql.toString(), new MapSqlParameterSource().addValue("id", id));
    }


    /**
     * 根据日志ID删除评论（回复）
     *
     * @param dailyId 日志ID
     * @return int
     * @author lyj
     * @since 2015-5-13
     */
    public int deleteByDailyId(final long dailyId) {
        StringBuilder sql = new StringBuilder("DELETE FROM t_daily_comment WHERE iDailyId = :dailyId ");

        return namedParameterJdbcTemplate.update(sql.toString(), new MapSqlParameterSource().addValue("dailyId", dailyId));
    }
    //</editor-fold>


    //<editor-fold desc="查询">
    /**
     * 根据日志ID获取回复列表
     *
     * @param dailyId 日志ID
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @return Page<DailyComment>
     * @author lyj
     * @since 2015-5-7
     */
    public Page<DailyComment> getAllComment(final long dailyId, final int pageNum, final int pageSize) {
        StringBuilder sql = new StringBuilder("SELECT dc.id,dc.sContent, dc.sCommentor,dc.dtCreate,dc.iCreatorId,te.sName,te.sPicture FROM t_daily_comment dc " +
                "JOIN t_teacher te ON dc.iCreatorId = te.id ");
        StringBuilder sqlCount = new StringBuilder("SELECT COUNT(dc.id) FROM t_daily_comment dc " +
                "JOIN t_teacher te ON dc.iCreatorId = te.id ");

        StringBuilder where = new StringBuilder(" WHERE 1 = 1");

        MapSqlParameterSource param = new MapSqlParameterSource();

        //过滤日志ID
        if (dailyId > 0) {
            log.debug("过滤日志IDdailyId > 0");

            where.append(" AND dc.iDailyId = :dailyId");
            param.addValue("dailyId", dailyId);
        }

        //获取查询总条数
        int total = namedParameterJdbcTemplate.queryForObject(sqlCount.append(where).toString(), param, Integer.class);

        //获取总条数
        if (total == 0) {
            log.debug("获取总条数total == 0");
            return new Page<>();
        }

        //追加limit限制
        where.append(getLimitStr(pageNum, pageSize));

        List<DailyComment> dailyCommentList = namedParameterJdbcTemplate.query(sql.append(where).toString(), param, new RowMapper<DailyComment>() {
            @Override
            public DailyComment mapRow(ResultSet resultSet, int i) throws SQLException {
                DailyComment dailyComment = new DailyComment();

                dailyComment.setId(resultSet.getLong("id"));
                dailyComment.setContent(resultSet.getString("sContent"));
                dailyComment.setCommentor(resultSet.getString("sCommentor"));
                dailyComment.setCreate(resultSet.getTimestamp("dtCreate"));
                dailyComment.setCreatorId(resultSet.getLong("iCreatorId"));
                dailyComment.setCreatorName(resultSet.getString("sName"));
                dailyComment.setCreatorPhoto(resultSet.getString("sPicture"));

                return dailyComment;
            }
        });

        log.debug("根据日志ID获取回复列表");
        return new Page<>(total, pageSize, pageNum, dailyCommentList);
    }


    /**
     * 获取日志回复明细
     *
     * @param id 回复ID
     * @return DailyComment
     * @author lyj
     * @since 2015-5-11
     */
    public DailyComment getDetail(final long id) {
        StringBuilder sql = new StringBuilder("SELECT iDailyId,iCommentId,iCreatorId,sContent,sCommentor FROM t_daily_comment WHERE id = :id");
        try {
            log.debug("获取日志回复明细");
            return namedParameterJdbcTemplate.queryForObject(sql.toString(), new MapSqlParameterSource().addValue("id", id), new RowMapper<DailyComment>() {
                @Override
                public DailyComment mapRow(ResultSet resultSet, int i) throws SQLException {
                    DailyComment dailyComment = new DailyComment();

                    dailyComment.setDailyId(resultSet.getLong("iDailyId"));
                    dailyComment.setCommentId(resultSet.getLong("iCommentId"));
                    dailyComment.setCreatorId(resultSet.getLong("iCreatorId"));
                    dailyComment.setContent(resultSet.getString("sContent"));
                    dailyComment.setCommentor(resultSet.getString("sCommentor"));

                    return dailyComment;
                }
            });
        } catch (EmptyResultDataAccessException ex) {
            log.debug("获取教学日志回复失败");

            log.warn("获取教学日志回复失败！");
            return null;
        }
    }
    //</editor-fold>


}
